# Configuration file


CONFIG_FILE = '/etc/pivelli/pivelli.ini'

from ConfigParser import SafeConfigParser, NoOptionError
from optparse import OptionParser

config = SafeConfigParser()
config.read([CONFIG_FILE])

parser = OptionParser()
config_values = []

def parse_item(item, retrieve_action, **extra_args):
	try:
		config_values.append((item, retrieve_action('general', item, **extra_args)),)
	except NoOptionError:
		pass

# Parse config file and get values
for item in ('bind_ip', 'gateway', 'peer_template', 'reg_template'):
	parse_item(item, config.get)

# Raw strings
for item in ('route_command', 'peer_config_name', 'reg_config_name'):
	parse_item(item, config.get, raw=True)
		
# Booleans
for item in ('write_config',):
	parse_item(item, config.getboolean)

# Parse numbers, if needed
cli_list = []
try:
	cli_list.append([n.strip() for n in config.get('general', 'numbers').split(',')])
except NoOptionError:
	pass

parser.set_defaults(**dict(config_values))

parser.add_option('-b', '--bind-ip', dest='bind_ip',
	help='Bind to this IP address for all requests')
parser.add_option('-g', '--gateway', action='store',
	help='The IP address of the Alice router')
parser.add_option('-e', '--enable', action='store_const', const='enable',
	dest='action', help='Enable the following CLIs', default=True)
parser.add_option('-a', '--enable-all', action='store_const', const='enable_all',
	dest='action', help='Enable all available CLIs')
parser.add_option('-d', '--disable', action='store_const', const='disable',
	dest='action', help='Disable all CLIs registered for this node')
parser.add_option('-s', '--status', action='store_const', const='status',
	dest='action', help='List all numbers')
parser.add_option('-p', '--peer-template', action='store',
	help='Set the template for the peer entry')
parser.add_option('-r', '--reg-template', action='store',
	help='Set the template for the register entry')
#parser.add_option('-u', '--user-template', action='store',
#	help='Set the template for the user entry')
parser.add_option('-w', '--write-config', action='store_true',
	help='Write Asterisk configuration files after registration')
parser.add_option('-v', '--verbose', action='store_true',
	default=False, help='Be verbose when activating numbers'
)

o, args = parser.parse_args()
cli_list += args

# Guess gateway
if not o.gateway:
	import re, os
	GW_RE = re.compile(r'^4\.1\.1\.1 via (\d+\.\d+\.\d+\.\d+)')
	try:
		route_string = os.popen('ip route get 4.1.1.1').read()
		o.gateway = GW_RE.match(route_string).group(1)
	except AttributeError:
		raise Exception, 'Cannot find default gateway. Use the -g/'\
			'--gateway option to set the IP address for the Alice gateway.'

# Ask for an interface
if not o.bind_ip:
	raise Exception, 'You must set the VoIP network IP address on the '\
		'command line or in the configuration file.'

